package com.yuxi.Dao.Impl;

import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.catalina.User;
import org.springframework.stereotype.Repository;

import com.yuxi.Config.ConfigStatic;
import com.yuxi.Dao.IExcelDao;
import com.yuxi.Entity.Information;
import com.yuxi.Entity.InformationFlow;
import com.yuxi.Entity.TaskDispatch;
import com.yuxi.Entity.UserInfo;
import com.yuxi.Request.InformationQuery;
import com.yuxi.Request.OwnQuery;
import com.yuxi.Request.Page;
import com.yuxi.excelEntity.Analysis;
import com.yuxi.excelEntity.ExportRsRj;
import com.yuxi.excelEntity.OwnWordInfo;
import com.yuxi.excelEntity.OwnWordRecord;
import com.yuxi.excelEntity.RealtimeTasks;
import com.yuxi.excelEntity.TaskReseachWord;
import com.yuxi.excelEntity.Tasks;
import com.yuxi.excelEntity.UserCustom;

@Repository
public class ExcelDaoImpl extends BaseDaoImpl<Serializable, Serializable> implements IExcelDao {

	@Override
	public List<Analysis> outExcelForAnalysis(int[] idArray) {
		StringBuffer idStr = new StringBuffer();
		for (int i = 0; i < idArray.length; i++) {
			if (i < idArray.length - 1) {
				idStr.append(idArray[i] + ",");
			} else {
				idStr.append(idArray[i]);
			}
		}

		String str = " new com.yuxi.excelEntity." + "Analysis(inforTable.id,inforTable.safetyPortNames,"
				+ " inforTable.informationSourceNames," + " inforTable.prisonName, inforTable.informationConternt,"
				+ " inforTable.mesure, " + "inforTable.zeRenPerSonNames,"
				+ " inforTable.zeRenTime, inforTable.zeRenRemark,inforTable.safetyPortId)";
		String hql = "select " + str + " from Information inforTable where inforTable.id in(" + idStr.toString() + ")";
		List list = super.find(hql);

		if (list.size() > 0 && list != null) {
			for (int i = 0; i < list.size(); i++) {
				Analysis cur = (Analysis) list.get(i);
				List curT = super.find("from InformationFlow where  informationId=? and flowId>? and flowId<?",
						cur.getId(), ConfigStatic.FLOWTABLE.get("FirstCheck"),
						ConfigStatic.FLOWTABLE.get("TaskDispatch"));
				Iterator<InformationFlow> curIt = curT.iterator();
				String curTask = "";
				while (curIt.hasNext()) {
					InformationFlow curF = curIt.next();
					String flowName = "";
					switch (curF.getFlowId()) {
					case 3:
						flowName = "初审";
						break;
					case 4:
						flowName = "复核";
						break;
					case 5:
						flowName = "审核";
						break;

					default:
						break;
					}
					curTask += flowName + ":" + curF.getOperation() + " \n\r";
				}
				cur.setId(i + 1);
				cur.setTaskS(curTask);
			}
			return list;
		}
		return null;
	}

	@Override
	public List<RealtimeTasks> outExcelForRealtimeTasks(int[] idArray) {
		StringBuffer idStr = new StringBuffer();
		for (int i = 0; i < idArray.length; i++) {
			if (i < idArray.length - 1) {
				idStr.append(idArray[i] + ",");
			} else {
				idStr.append(idArray[i]);
			}
		}
		String str = " new com.yuxi.excelEntity.RealtimeTasks(" + "inforTable.informationConternt,"
				+ " inforTable.informationClassificationId," + " inforTable.mesure, inforTable.standard, "
				+ "inforTable.taskDispatchTime," + " taskTable.personDispatchName, " + "inforTable.zeRenTime, "
				+ "taskTable.taskCompletion," + " taskTable.perSonLiableName, " + "taskTable.remark)";
		String hql = "select " + str + " from Information inforTable,"
				+ "TaskDispatch taskTable where inforTable.id=taskTable.informationId and inforTable.id in("
				+ idStr.toString() + ")";
		List list = super.find(hql);
		if (list.size() > 0 && list != null) {
			if (list != null) {
				for (int i = 0; i < list.size(); i++) {
					RealtimeTasks s = (RealtimeTasks) list.get(i);
					s.setId(i + 1);
				}
			}

			return list;
		}

		return null;
	}

	@Override
	public List<Tasks> outExcelForTasks(int[] idArray) {
		StringBuffer idStr = new StringBuffer();
		for (int i = 0; i < idArray.length; i++) {
			if (i < idArray.length - 1) {
				idStr.append(idArray[i] + ",");
			} else {
				idStr.append(idArray[i]);
			}
		}
		String str = " new com.yuxi.excelEntity.Tasks(inforTable.informationConternt, "
				+ "inforTable.informationClassificationNames, "
				+ "inforTable.mesure, inforTable.standard, inforTable.taskDispatchTime, inforTable.zeRenTime, taskTable.taskCompletion, taskTable.perSonLiableName,"
				+ " inforTable.zeRenRemark,taskTable.perSonLiableName)";
		String hql = "select " + str
				+ " from Information inforTable,TaskDispatch taskTable where inforTable.id=taskTable.informationId and inforTable.id in("
				+ idStr.toString() + ")";
		List list = super.find(hql);
		if (list != null) {
			for (int i = 0; i < list.size(); i++) {
				Tasks s = (Tasks) list.get(i);
				s.setId(i + 1);
			}
		}
		return list;
	}

	

	@Override
	public List<Information> getInforList(InformationQuery query, Integer userId) {
		StringBuilder str = new StringBuilder("");
		if (!query.getInformationSource().equals("%")) {
			String[] source = query.getInformationSource().split(",");
			str.append(" and (");
			for (int i = 0; i < source.length; i++) {
				if (i >= 1) {
					str.append(" or ");
				}
				str.append(" informationSourceID like '%," + source[i] + ",%' ");
			}
			str.append(")");
		}

		String hql = "from Information where  userId=? and createTime BETWEEN ? and ? and " + "  safetyPortId=? "
				+ str.toString();
		return find(hql, userId, query.getStartTimestamp(), query.getEndTimestamp(), query.getSalfPort());
	}

	@Override
	public List<ExportRsRj> getRsRjList(String startTime,String endTime,int userId) {
		try {   
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
	        Date date = simpleDateFormat.parse(startTime);
	        long startT = date.getTime();
	        
	        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
	        Date date1;				
			date1 = simpleDateFormat1.parse(endTime);			
			long endT = date1.getTime()+(24*60*60*1000-1000);	
			//System.out.println(startT+":"+endT);
			return super.find(
				"select distinct  new com.yuxi.excelEntity.ExportRsRj"
						+ "(infoTable.prisonName, infoTable.informationConternt, infoTable.mesure, infoTable.taskCompletion, infoFlowtable.remark)"
						+ " from Information as infoTable,InformationFlow infoFlowtable where infoTable.id=infoFlowtable.informationId and infoFlowtable.lastFlowId=? and infoTable.informationSourceNames like ? and infoTable.createTime BETWEEN ? AND ?  and infoFlowtable.userId=?",
				ConfigStatic.FLOWTABLE.get("FirstCheck"),"%日搜日解%",startT,endT,userId);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

	@Override
	public List<TaskReseachWord> getTaskReseach(Integer[] arrayStr) {
		if (arrayStr == null || arrayStr.length < 1) {
			List<TaskReseachWord> rs = new ArrayList<TaskReseachWord>();
			rs.add(new TaskReseachWord());
			return rs;
		}
		StringBuilder str = new StringBuilder();
		for (int i = 0; i < arrayStr.length; i++) {
			if (i > 0) {
				str.append(",");
			}
			str.append(arrayStr[i]);
		}
		
		String hql = "Select new com.yuxi.excelEntity.TaskReseachWord(infoTable.informationSortNames,infoTable.informationConternt,"
				+ "infoTable.mesure, infoTable.zeRenPerSonNames, infoTable.zeRenTime,infoTable.taskCompletion,infoTable.safetyPortId)" 
				+ " from Information as infoTable where infoTable.id in ("+str.toString()+")";
		List<TaskReseachWord> rs=super.find(hql);
		return rs;
	}

	@Override
	public List<UserCustom> getInforList(Integer[] array) {
		if (array == null || array.length < 1) {
			List<UserCustom> rs = new ArrayList<UserCustom>();
			rs.add(new UserCustom());
			return rs;
		}
		StringBuilder str = new StringBuilder();
		for (int i = 0; i < array.length; i++) {
			if (i > 0) {
				str.append(",");
			}
			str.append(array[i]);
			
		}
		String uStr="new com.yuxi.excelEntity.UserCustom(infoTable.id,"
				+ " infoTable.informationAccount,"
				+ " infoTable.prisonName,"
				+ " infoTable.informationSourceNames,"
				+ " infoTable.inputPerSonNames,"
				+ " infoTable.informationProfile, infoTable.informationConternt,"
				+ " infoTable.mesure, infoTable.standard, "
				+ "infoTable.informationClassificationNames, infoTable.informationSortNames, "
				+ "infoTable.taskCompletion, infoTable.safetyPortNames,"
				+ " infoTable.createTime, infoTable.flowName,"
				+ " infoTable.zeRenPerSonNames, infoTable.zeRenTime,"
				+ " infoTable.zeRenRemark, infoTable.taskDispatchName, "
				+ "infoTable.taskDispatchTime, infoTable.prisonName,infoTable.safetyPortId,infoTable.userId)";
		return super.find(
				"select "+uStr
						+ " from Information as infoTable where infoTable.id in ("
						+ str.toString() + ")   order by field(infoTable.id," + str.toString() + ")");
	}

	@Override
	public Page<OwnWordRecord> getRecord(OwnQuery query, Page<OwnWordRecord> p, UserInfo u) {
		if(query.getUserABId()!=null){
			String hql=" FROM  OwnWordRecord where state=1 and (createUserId=? or userBId=?) and (createUserId=? or userBId=?)  and id NOT in(SELECT b.recordId FROM OwnWordRecord as a,OwnwordRecordBorwser as b WHERE a.id=b.recordId and b.userId=?)";
			return super.splitPageQuery(hql, p, query.getUserABId(), query.getUserABId(), u.getUserId(),u.getUserId(),u.getUserId());
		}else{
			String hql=" FROM  OwnWordRecord where state=1  and (createUserId=? or userBId=?)  and id NOT in(SELECT b.recordId FROM OwnWordRecord as a,OwnwordRecordBorwser as b WHERE a.id=b.recordId and b.userId=?)";
			return super.splitPageQuery(hql, p, u.getUserId(),u.getUserId(),u.getUserId());
		}
	}

	@Override
	public Page<OwnWordRecord> getAlreadyRecord(OwnQuery query, Page<OwnWordRecord> p, UserInfo u) {
		if(query.getUserABId()!=null){
			String hql=" FROM  OwnWordRecord where (createUserId=? or userBId=?) and id  in(SELECT b.recordId FROM OwnWordRecord as a,OwnwordRecordBorwser as b WHERE a.id=b.recordId and b.userId=?)";
			return super.splitPageQuery(hql, p, query.getUserABId(), query.getUserABId(), u.getUserId());
		}else{
			String hql=" FROM  OwnWordRecord where (createUserId=? or userBId=?) and id  in(SELECT b.recordId FROM OwnWordRecord as a,OwnwordRecordBorwser as b WHERE a.id=b.recordId and b.userId=?)";
			return super.splitPageQuery(hql, p, u.getUserId(), u.getUserId(), u.getUserId());
		}
	}


	
	@Override
	public List<OwnWordInfo> outWordForInformationByIdArray(String start,String end,int userId,String portQueryStr) {
		
		try {
	        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
	        Date date = simpleDateFormat.parse(start);
	        long startT = date.getTime();
	        
	        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
	        Date date1;	
	        
			date1 = simpleDateFormat1.parse(end);
			long endT = date1.getTime()+(24*60*60*1000-1000);
			List<Map<String, Object>> rs = super.executeSql("select " + "infoTable.informationConternt,"
					+ "infoTable.inputPerSonNames," + "infoTable.mesure," + "infoTable.zeRenTime,"
					+ "infoTable.taskCompletion," + "infoTable.zeRenPerSonNames," + "commrecTable.informationQualityName,"
					+ "commrecTable.taskCompletionName,infoTable.safetyPortNames,infoTable.safetyPortId" + " from " + "Information as infoTable left join "
					+ "CommentRecord as commrecTable  on ( infoTable.id=commrecTable.informationId) " + "where "
					+ "infoTable.safetyPortId in ("+portQueryStr+")  and infoTable.createTime BETWEEN ? AND ?  and infoTable.userId=? order by infoTable.createTime",startT,endT,userId);
			List<OwnWordInfo> rso = new ArrayList<OwnWordInfo>();
			for (Map<String, Object> item : rs) {
				OwnWordInfo ow = new OwnWordInfo(item.get("informationConternt"), item.get("inputPerSonNames"),
						item.get("mesure"), item.get("zeRenTime"), item.get("taskCompletion"), item.get("zeRenPerSonNames"),
						item.get("informationQualityName"), item.get("taskCompletionName"),item.get("safetyPortNames"),item.get("safetyPortId"));
				rso.add(ow);
			}
			return rso;
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
		

	}

	@Override
	public void deleteOwnById(Integer id) {	
		super.delete(" DELETE FROM OwnWordRecord WHERE id=?", id);
		super.delete(" DELETE FROM OwnwordRecordBorwser WHERE recordId=?", id);
	}

}
